package com.dituhui.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.dituhui.gps.vo.GPSLine;
import com.dituhui.gps.vo.GPSPoint;
import com.dituhui.tool.io.Constants;
import com.dituhui.tool.io.RedisTool;
import com.dituhui.tool.util.DateUtil;
import com.dituhui.tool.util.StringUtil;

import net.sf.json.JSONObject;

/**
 * 支持微信客户端的上传位置服务
 * 
 * @author liweigu
 * 
 */
public class DoUploadGPSPos extends HttpServlet {
	private static final Logger LOGGER = Logger.getLogger(DoUploadGPSPos.class);
	private static String redisUrl = Constants.getValue("REDIS.HOST", "gps_config.properties");;
	private static int redisPort = Integer.parseInt(Constants.getValue("REDIS.PORT", "gps_config.properties"));
	private static String redisPwd = Constants.getValue("REDIS.PWD", "gps_config.properties");

	public void init() throws ServletException {
		LOGGER.info("redisUrl=" + redisUrl);
	}

	// 1)上传坐标
	// http://ip:port/gpsPos?cmd=upload&type=basket&a=test&g=106.0^30.0^1^20170206113400
	// 2)查询坐标
	// http://gps.dituhui.com/wxweb/uploadGPSPos?cmd=list&type=basket&a=test
	public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String accountId = request.getParameter("a");
		String command = request.getParameter("cmd");
		String type = request.getParameter("type");
		// 跨域访问
		String callbacks = (request.getParameter("callbacks") != null) ? request.getParameter("callbacks") : null;

		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();

		String content = "";
		// 上传坐标
		if (accountId == null || accountId.length() == 0) {
			String message = "参数非法，应传入accountId";
			LOGGER.info(message);
			content = message;
		} else if (type == null || type.length() == 0) {
			String message = "参数非法，应传入type";
			LOGGER.info(message);
			content = message;
		} else {
			if ("upload".equalsIgnoreCase(command)) {
				String gpsData = request.getParameter("g");
				if (gpsData != null && gpsData.contains(StringUtil.AngularBracket)) {
					try {
						String[] arr = gpsData.split(StringUtil.AngularBracketForSplit);
						double x = Double.parseDouble(arr[0]);
						double y = Double.parseDouble(arr[1]);
						int accuracy = Integer.parseInt(arr[2]);
						Date gpsTime = DateUtil.getShortGPSTimeFormat().parse(arr[3]);
						GPSPoint gpsPoint = new GPSPoint(x, y);
						gpsPoint.setGPSTime(gpsTime);
						gpsPoint.setAccuracy(accuracy);
						gpsPoint.setAccountId(accountId);

						RedisTool redisTool = new RedisTool();
						String key = type + StringUtil.Underline + accountId;
						redisTool.setString(key, gpsPoint.toCSVString(), redisUrl, redisPort, redisPwd);
					} catch (NumberFormatException e) {
						e.printStackTrace();
					} catch (ParseException e) {
						e.printStackTrace();
					}
				}
			} else if ("list".equalsIgnoreCase(command)) {
				try {
					StringBuilder output = new StringBuilder();
					RedisTool redisTool = new RedisTool();
					String keysQueryClause = type + StringUtil.Underline + "*";
					Set<String> redisKeys = redisTool.getKeys(keysQueryClause, redisUrl, redisPort, redisPwd);
					List<GPSPoint> gpsPoints = new ArrayList<GPSPoint>();
					for (String redisKey : redisKeys) {
						String value = redisTool.getString(redisKey, redisUrl, redisPort, redisPwd);
						GPSPoint gpsPoint = GPSPoint.parseCSVString(value);
						gpsPoints.add(gpsPoint);
					}
					GPSLine.sortByTime(gpsPoints);
					if (callbacks == null) {
						output.append("gpsPoints.size() = " + gpsPoints.size());
						output.append("<br>");
						// 最多输出15条
						int n = 15;
						String count = request.getParameter("count");
						if (count != null && count.length() > 0) {
							try {
								n = Integer.parseInt(count);
							} catch (Exception e) {
								LOGGER.info("解析count失败，count=" + count);
							}
						}
						// 倒序
						for (int i = gpsPoints.size() - 1; i >= 0 && i >= gpsPoints.size() - n; i--) {
							GPSPoint gpsPoint = gpsPoints.get(i);
							output.append(gpsPoint.toString());
							output.append("<br>");
						}
						content = output.toString();
					} else {
						GPSLine gpsLine = new GPSLine();
						gpsLine.setGPSPoints(gpsPoints);
						content = gpsLine.toCSVString();
					}
				} catch (Exception e) {
					String message = "查询发生异常。";
					LOGGER.warn(message, e);
				}
			} else {
				String message = "参数非法，command错误";
				LOGGER.info(message);
				content = message;
			}
		}

		StringBuilder output = new StringBuilder();
		if (callbacks != null && callbacks.length() > 0) {
			output.append(callbacks);
			output.append("(");
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("data", content);
			output.append(jsonObject.toString());
			output.append(")");
		} else {
			output.append(content);
		}
		out.print(output.toString());

		out.flush();
		out.close();
	}
}
